package com.sunfeng.chap2;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2021/10/8  14:47
 */
public class Test2_1 {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File("d:\\b.txt"));
        FileChannel fileChannel = fileInputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(5);
        int readLength = fileChannel.read(byteBuffer);
        System.out.println(byteBuffer);
        System.out.println(readLength);
        // 将下面代码添加注释,那么在执行read()方法时
        // 返回值是0，因为byteBuffer没有remaining剩余空间
        // byteBuffer.clear();
        readLength = fileChannel.read(byteBuffer);
        System.out.println(byteBuffer);
        System.out.println(readLength);
        // 执行clear()方法，使缓冲区状态还原
        byteBuffer.clear();
        readLength = fileChannel.read(byteBuffer);
        System.out.println(byteBuffer);
        System.out.println(readLength);

    }
}
